/* 
 * File:   MajBatch.cpp
 * Author: Morpheus
 * 
 * Created on 29 juillet 2014, 14:58
 */

#include "MajBatch.h"
#include <QtCore/qdir.h>
#include <QtCore/qfile.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qsettings.h>
#include <QtCore/qdebug.h>
#include <QtWidgets/qapplication.h>
#include <QtCore/qthread.h>

#include "DAOBatchMerge.h"

#define My_TIME_SLEEP 1000

class BatchUnitTmp{
public:
    BatchUnitTmp(){};
    BatchUnitTmp(const BatchUnitTmp& orig)
     : uuid(orig.uuid), filePath(orig.filePath), pattern(orig.pattern) {};
    virtual ~BatchUnitTmp(){};
    QDataStream& load(QDataStream& out, const int& v = 1){
        out >> uuid >> filePath >> pattern;
        return out;
    }

    QString uuid;
    QString filePath;
    QString pattern;
};
class BatchMergeTmp{
public:
    BatchMergeTmp(){};
    BatchMergeTmp(const BatchMergeTmp& orig)
     : uuid(orig.uuid), created(orig.created), lastModified(orig.lastModified),
     name(orig.name), saveFilePatern(orig.saveFilePatern), saveFileFormat(orig.saveFileFormat),
     doWthSucces(orig.doWthSucces), batchUnits(orig.batchUnits) {};
    virtual ~BatchMergeTmp(){};
    
    QDataStream& load(QDataStream& out, const int& v = 1){
        QString tmp;
        out >> tmp;
        if(tmp != QString("MyBatchMerge")){
            out.setStatus(QDataStream::ReadCorruptData);
            return out;
        }
        out >> uuid;
        out >> name;
        out >> saveFilePatern;
        out >> saveFileFormat;
        out >> doWthSucces;
        out >> created;
        out >> lastModified;
        {
            batchUnits.clear();
            quint32 c;
            out >> c;
            batchUnits.reserve(c);
            for(quint32 i = 0; i < c; ++i)
            {
                BatchUnitTmp t;
                t.load(out, v);
                batchUnits.append(t);
            }
        }
        
        return out;
    }
   
    QString uuid;
    QDateTime created;
    QDateTime lastModified;
    QString name;
    QString saveFilePatern;
    QString saveFileFormat;
    bool doWthSucces;
    QList<BatchUnitTmp> batchUnits;
};

MajBatch::MajBatch(QObject* parent)
 : QObject(parent) {
}

MajBatch::~MajBatch() {
}

void MajBatch::checkUpdate() {
    QThread::msleep(My_TIME_SLEEP);
    emit showMessage(tr("Vérification des Mise à Jours"));
    QThread::msleep(My_TIME_SLEEP);
    
    QDir dir(qApp->applicationDirPath());
    if(!dir.exists("./FileMergerData")){
        dir.mkdir("./FileMergerData");
    }
    QSettings setting(dir.absoluteFilePath("./FileMergerData/FileMerger.ini"), QSettings::IniFormat, this);

    setting.beginGroup(tr("General"));
    QString version = setting.value(tr("Version"), tr("1.0.0.4")).toString();
    if(version == qApp->applicationVersion()){
        emit showMessage("Application et Données à jours");
        QThread::msleep(My_TIME_SLEEP);
    }else{
        if(version <= "1.0.0.4"){
            v1_0_0_4Tov1_0_0_5();
        }
    }
    emit showMessage("Chargement des Données");
    QThread::msleep(My_TIME_SLEEP);
}

void MajBatch::v1_0_0_4Tov1_0_0_5() {
    emit showMessage(tr("Mise à Jours de 1.0.0.4 vers 1.0.0.5"));
    // déplacer le fichier init
    QDir dir(qApp->applicationDirPath());
    QString version = "1.0.0.5";
    if(QFile::exists("/FileMergerData/FileMerger.ini")){
        {
            QSettings setting(dir.absoluteFilePath("/FileMergerData/FileMerger.ini"), QSettings::IniFormat, this);
            setting.beginGroup(tr("General"));
            setting.setValue(tr("Version"), version);
            setting.sync();     // force rewrite other values
        }
        QFile::rename("/FileMergerData/FileMerger.ini", dir.absoluteFilePath("./FileMergerData/FileMerger.ini"));
    }
    
    QFile file(dir.absoluteFilePath("./FileMergerData/MyBatchSavedList.dat"));
    if(!file.exists())
        return;
    QList<BatchMergeTmp> batchMergeOldList;
    if(file.open(QIODevice::ReadOnly)){
        QDataStream out(&file);
        quint32 c;
        out >> c;
        batchMergeOldList.reserve(c);
        for(quint32 i = 0; i < c; ++i){
            BatchMergeTmp batchMergeOld;
            batchMergeOld.load(out);
            batchMergeOldList.append(batchMergeOld);
        }
    }else{
        return;
    }
    double size = batchMergeOldList.size();
    while(!batchMergeOldList.isEmpty()){
        // make batchMerge new version
        BatchMergeTmp batchMergeOld = batchMergeOldList.takeFirst();
        MyBatchMerge batchMergeNew;
        batchMergeNew.setBlockUpdate(true);
//        batchMergeNew.setUUID(batchMergeOld.uuid);
        batchMergeNew.setCreatedDate(batchMergeOld.created);
        batchMergeNew.setLastModifiedDate(batchMergeOld.lastModified);
        batchMergeNew.setName(batchMergeOld.name);
        batchMergeNew.setSaveFilePatern(batchMergeOld.saveFilePatern);
        batchMergeNew.setSaveFileFormat(batchMergeOld.saveFileFormat);
        batchMergeNew.setDoWithSuccess(batchMergeOld.doWthSucces);
        QList<MyBatchUnit> l;
        while(!batchMergeOld.batchUnits.isEmpty()){
            BatchUnitTmp batchUnitOld = batchMergeOld.batchUnits.takeFirst();
            MyBatchUnit batchUnitNew;
            batchUnitNew.setUUID(batchUnitOld.uuid);
            batchUnitNew.setFilePath(batchUnitOld.filePath);
            batchUnitNew.setContentText(batchUnitOld.pattern);
            l.append(batchUnitNew);
        }
        batchMergeNew.setBatchList(l);
        batchMergeNew.setBlockUpdate(false);
        
        DAOBatchMerge::self()->saveBatchMerge(batchMergeNew);
        
        int percent = ((size - batchMergeOldList.size()) / size) * 100.0;
        emit showMessage(tr("Mise à Jours des Données %1 %").arg(percent));
    }
    
}
